<script setup lang="ts">
import mitt from 'mitt'
import { ViewManage, ViewTree } from './components'
import type { IndicatorInfo } from '@/types'
import { indicatorApi, modelConfigApi } from '@/api'

const show = ref(true)
const loading = ref(true)
const tableData = shallowRef<IndicatorInfo[]>([])

const emitter = mitt<{
  'query:model-configs': {
    modelType: string
    callback?: () => void
  }
  'query:point-indicators': number
  'toggle-show:tree': boolean
}>()

provide('model-configs:emitter', emitter)

async function getIndicators(pointId: number = 0) {
  loading.value = true
  try {
    const { data } = await indicatorApi.loadPointList(
      pointId,
    )
    tableData.value = data || []
  }
  catch (e) {
  }
  finally {
    loading.value = false
  }
}

async function getConfigs({
  modelType,
  callback,
}: {
  modelType: string
  callback?: () => void
}) {
  loading.value = true
  try {
    const { data } = await modelConfigApi.getMonitorConfig(
      modelType,
    )
    tableData.value = data || []
    callback?.()
  }
  catch (e) {
  }
  finally {
    loading.value = false
  }
}

function toggleShowTree(bool: boolean) {
  show.value = bool
}

onBeforeUnmount(() => {
  emitter.off('query:model-configs', getConfigs)
  emitter.off('query:point-indicators', getIndicators)
  emitter.off('toggle-show:tree', toggleShowTree)
})
onMounted(() => {
  emitter.on('query:model-configs', getConfigs)
  emitter.on('query:point-indicators', getIndicators)
  emitter.on('toggle-show:tree', toggleShowTree)

  getIndicators()
})
</script>

<template>
  <div
    class="padding-sm align-center relative box-border flex gap-sm container"
  >
    <ViewTree v-show="show" />
    <ViewManage
      :loading="loading"
      :table-data="tableData"
    />
  </div>
</template>
